package com.xbongbong.workflow.service.strategy.node.impl;

import com.alibaba.fastjson.JSON;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.config.enums.WorkflowTaskLogStatusEnum;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.enums.BusinessRuleExecuteEnum;
import com.xbongbong.paas.enums.PlatFormEnum;
import com.xbongbong.paas.exception.WorkflowException;
import com.xbongbong.sys.help.PackageHelp;
import com.xbongbong.paas.pojo.dto.FormDataDeleteBatchDTO;
import com.xbongbong.paas.pojo.vo.FormDataDeleteBatchVO;
import com.xbongbong.paas.service.WorkflowOperatorDataService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.pro.enums.PackageTypeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.formdata.pojo.SaasNeedRedundantAttrPojo;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.sys.model.UserModel;
import com.xbongbong.workflow.domain.entity.WorkflowNodeEntity;
import com.xbongbong.workflow.enums.WorkflowNodeTypeEnum;
import com.xbongbong.workflow.pojo.Data;
import com.xbongbong.workflow.pojo.FlowData;
import com.xbongbong.workflow.pojo.FlowDatas;
import com.xbongbong.workflow.pojo.WorkflowProcessResultPojo;
import com.xbongbong.workflow.pojo.WorkflowTransferPOJO;
import com.xbongbong.workflow.pojo.nodes.DeleteRecordNode;
import com.xbongbong.workflow.service.strategy.node.AbstractWorkflowNodeStrategy;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.common.util.set.Sets;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;

/**
 * 删除记录节点
 * @author 魏荣杰
 */
@Service
@Slf4j
public class WorkflowNodeDeleteStrategy extends AbstractWorkflowNodeStrategy {

    @Resource
    private WorkflowOperatorDataService workflowOperatorDataService;
    @Resource
    private PackageHelp packageHelp;
    @Resource
    private UserModel userModel;
    @Override
    public String type() {
        return WorkflowNodeTypeEnum.DELETE_NODE.getName();
    }

    @Override
    public void before(WorkflowTransferPOJO workflowTransferPOJO) {
        super.before(workflowTransferPOJO);
    }

    @Override
    public WorkflowProcessResultPojo process(WorkflowTransferPOJO workflowTransferPOJO, WorkflowNodeEntity workflowNodeEntity, Long lastNodeId, SaasNeedRedundantAttrPojo saasNeedRedundantAttrPojo) {
        DeleteRecordNode deleteRecordNode = JSON.parseObject(workflowNodeEntity.getConfigData(), DeleteRecordNode.class);
        if (null == deleteRecordNode) {
            log.warn("获取删除数据节点失败,不做处理");
            return new WorkflowProcessResultPojo(true, false);
        }

        //要更新的id
        Set<Long> dataIds = Sets.newHashSet();
        try {
            String corpid = workflowTransferPOJO.getCorpid();
            Integer feeType = packageHelp.getFeeType(corpid);
            if (!Objects.equals(PackageTypeEnum.ULTIMATE.getType(), feeType)) {
                logger(workflowTransferPOJO, workflowNodeEntity, WorkflowTaskLogStatusEnum.PASS, new WorkflowException(MessageConstant.WORKFLOW_NODE_VERSION_NOT_SUPPORT));
                return new WorkflowProcessResultPojo(true, false);
            }
            //触发表单
            if (Objects.equals(deleteRecordNode.getTriggerNodeFlag(), BasicConstant.ONE)) {
                Data data = workflowTransferPOJO.getData();
                dataIds.add(data.getId());
                
            } else {
                //流转数据
                FlowDatas flowDatas = workflowTransferPOJO.getFlowDatas();
                Optional.ofNullable(flowDatas)
                        .map(FlowDatas::getNodeIdMap)
                        .map(t -> t.get(deleteRecordNode.getWorkflowNodeId().toString()))
                        .map(FlowData::getIds)
                        .ifPresent(dataIds::addAll);
            }
            //校验数量
            //数据更新条数为0
            if (dataIds.isEmpty()) {
                logger(workflowTransferPOJO, workflowNodeEntity, WorkflowTaskLogStatusEnum.PASS, new WorkflowException(BusinessRuleExecuteEnum.NO_DATA.getMessage()));
                return new WorkflowProcessResultPojo(true, false);
            }
            // 增加 i18n 参数
            FormDataDeleteBatchDTO formDataDeleteBatchDTO = new FormDataDeleteBatchDTO();
            formDataDeleteBatchDTO.setDataIdList(new ArrayList<>(dataIds));
            formDataDeleteBatchDTO.setIsBusinessRule(1);
            formDataDeleteBatchDTO.setCorpid(workflowNodeEntity.getCorpid());
            formDataDeleteBatchDTO.setUserId(workflowTransferPOJO.getUser().getUserId());
            formDataDeleteBatchDTO.setPlatform(PlatFormEnum.INTERNAL.getValue());
            formDataDeleteBatchDTO.setBusinessType(workflowNodeEntity.getBusinessType());
            formDataDeleteBatchDTO.setFormId(workflowNodeEntity.getFormId());
            formDataDeleteBatchDTO.setAppId(workflowNodeEntity.getAppId());
            formDataDeleteBatchDTO.setMenuId(workflowNodeEntity.getMenuId());
            formDataDeleteBatchDTO.setSaasMark(workflowNodeEntity.getSaasMark());
            FormDataDeleteBatchVO formDataDeleteBatchVO = workflowOperatorDataService.delete(formDataDeleteBatchDTO);

            // 删除失败的原因（客户等有返回数据的）
            if (Objects.nonNull(formDataDeleteBatchVO) && CollectionsUtil.isNotEmpty(formDataDeleteBatchVO.getErrorDataList())) {
                //这里防止返回的提示为空,影响下面的更新日志
                String errorMsg = StringUtil.isEmpty(formDataDeleteBatchVO.getErrorDataMemo(), true)
                        ? "" : formDataDeleteBatchVO.getErrorDataMemo() + "：" + StringUtils.join(formDataDeleteBatchVO.getErrorDataList(), "；");
                log.info("businessRule onlyDelete not delete ：" + JSON.toJSONString(formDataDeleteBatchVO.getErrorDataList()));
                Integer count = dataIds.size() - formDataDeleteBatchVO.getErrorDataList().size();
                count = count < 0 ? 0 : count;
                errorMsg =  String.format(I18nMessageUtil.getMessage(MessageConstant.WORKFLOW_NODE_PASS_DELETE_DATA), count) + "；" + errorMsg ;
                if (Objects.equals(count, 0)) {
                    logger(workflowTransferPOJO, workflowNodeEntity, WorkflowTaskLogStatusEnum.SUSPEND, new WorkflowException(errorMsg));
                    return new WorkflowProcessResultPojo(false, false, true);
                } else {
                    logger(workflowTransferPOJO, workflowNodeEntity, WorkflowTaskLogStatusEnum.PASS, new WorkflowException(errorMsg));
                }
            } else {
                String errorMsg =  String.format(I18nMessageUtil.getMessage(MessageConstant.WORKFLOW_NODE_PASS_DELETE_DATA), dataIds.size());
                logger(workflowTransferPOJO, workflowNodeEntity, WorkflowTaskLogStatusEnum.PASS, new WorkflowException(errorMsg));
            }

        } catch (XbbException e) {
            log.error("工作流删除节点捕获XbbException", e);
            //这里防止返回的提示为空,影响下面的更新日志
            String errorMsg = StringUtil.isEmpty(e.getMsg(), true) ? SystemErrorCodeEnum.API_ERROR_100001.getMsg() : e.getMsg();
            logger(workflowTransferPOJO, workflowNodeEntity, WorkflowTaskLogStatusEnum.FAIL, new WorkflowException(errorMsg));
            return new WorkflowProcessResultPojo(false, false);
        } catch (Exception e) {
            log.error("工作流删除节点捕获Exception", e);
            logger(workflowTransferPOJO, workflowNodeEntity, WorkflowTaskLogStatusEnum.FAIL, new WorkflowException(e.getMessage()));
            return new WorkflowProcessResultPojo(false, false);
        }
        return new WorkflowProcessResultPojo(true, false);
    }

    @Override
    public void after(WorkflowTransferPOJO workflowTransferPOJO, WorkflowNodeEntity workflowNodeEntity) {
        super.after(workflowTransferPOJO, workflowNodeEntity);
    }

    @Override
    public void check() {
        super.check();
    }

    @Override
    public void logger(WorkflowTransferPOJO workflowTransferPOJO, WorkflowNodeEntity nodeEntity, WorkflowTaskLogStatusEnum workflowTaskLogStatusEnum, WorkflowException workflowException) {
        super.logger(workflowTransferPOJO, nodeEntity, workflowTaskLogStatusEnum, workflowException);
    }
}
